package com.ourhours.redismq;/**
 * Created by dingxiangyong on 2017/3/12.
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息监听器
 * @auth xiangyong.ding
 * 2017/3/12 21:28
 **/
@Service
public class MessageMonitor {
	/**
	 * @author lizongyue
	 * @date 2018-02-07
	 */
	@Autowired
	RedisUtil redisUtil;
    
    /**
     * 获取所有的队列和未消费消息数量
     * @return
     */
    public List<RedisQueue> getAllQueues(){
    		List<RedisQueue> queueList = new ArrayList<RedisQueue>();
    		//获取所有的队列（QUEUE.开头的key）,因为当消息全部被取走后，keys就查不到KEY了，所以不能用keys来查询
//    		Set<byte[]> queueBytesSet = (Set<byte[]>) redisTemplate.execute(new RedisCallback<Set<byte[]>>() {
//			public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
//				return connection.keys((MtConstant.KEY_PREFIX+"*").getBytes());
//			}
//		});
    		Set<String> queueSet = redisUtil.smembers(MtConstant.QUEUE_NAME_SET);
    		//获取进队消息个数
    		Map<String, String> inCountMap = redisUtil.hgetAll(MtConstant.QUEUE_IN_NUMBERS);
    		//获取出队消息个数
    		Map<String, String> outCountMap = redisUtil.hgetAll(MtConstant.QUEUE_OUT_NUMBERS);
    		for(String queueName : queueSet) {
    			int count = this.getQueueMessageCount(queueName);
    			
    			Integer inNum = 0,outNum=0;
    			try {
    				inNum = Integer.parseInt(inCountMap.get(queueName));
			} catch (Exception e) {}
    			try {
    				outNum = Integer.parseInt(outCountMap.get(queueName));
			} catch (Exception e) {}
    			RedisQueue rq = new RedisQueue(queueName, count,inNum,outNum);
    			queueList.add(rq);
    		}
    		return queueList;
    }
    
    /**
	 * 删除所有消息
	 * @param queueName
	 */
	public Long purgeAll(final String queueName) {
		Long ret = redisUtil.del(queueName);
		return ret;
	}
	/**
	 * 删除队列
	 * @param queueName
	 */
	public Long deleteQueue(final String queueName) {
		//移除名称集合中的对列名
		redisUtil.srem(MtConstant.QUEUE_NAME_SET,queueName);
		redisUtil.hset(MtConstant.QUEUE_IN_NUMBERS,queueName,"0");
		redisUtil.hset(MtConstant.QUEUE_OUT_NUMBERS,queueName,"0");
		Long ret = redisUtil.del(queueName);
		return ret;
	}

    /**
     * 获取待处理消息个数
     * @param queueName 
     * @return
     */
    public int getQueueMessageCount(final String queueName){
    		Integer length = redisUtil.llen(queueName).intValue();
        return length;
    }
    
}
